package com.jhd.jiangxi.activity.main;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.TimePickerView;
import com.jhd.jiangxi.R;
import com.jhd.jiangxi.ScanApplication;
import com.jhd.jiangxi.UtilHelper;
import com.jhd.jiangxi.activity.scan.in.scrap.ScrapInActivity;
import com.jhd.jiangxi.service.GetVaccineService;
import com.jhd.jiangxi.service.VaccineService;
import com.jhd.jiangxi.util.ScanUtil;
import com.jhd.jiangxi.util.TextDialog;
import com.jhd.jiangxi.util.VaccineContain;
import com.jhd.jiangxi.vo.Approval;
import com.jhd.jiangxi.vo.GlobalDictionary;
import com.jhd.jiangxi.vo.JsonForResult;
import com.jhd.jiangxi.vo.Person;
import com.jhd.jiangxi.vo.PiatsInfo;
import com.jhd.jiangxi.vo.PiatsShow;
import com.jhd.jiangxi.vo.PriceBook;
import com.jhd.jiangxi.vo.RefDept;
import com.jhd.jiangxi.vo.StorageChoose;
import com.jhd.jiangxi.vo.StorageInfo;

import net.zigin.commons.util.CollectionUtil;
import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class BaseActivity extends ScanApi {
    //    SharedPreferences _user = null;
    protected ScanApplication application;
    protected List<RefDept> deptList=null;//供货单位
    protected List<Approval> approvalList=null;
    protected List<PriceBook> priceBook=null;
    protected List<Person> personList=null;
    protected static List<PiatsInfo> piatsInfos=new ArrayList<>();
    private AlertDialog _alertDialog=null;
    private LinearLayout linearLayout;
    private RecyclerView rvStorage;
    private Button btnStorage;
    private DetailAdapter detailAdapter;
    protected List<PiatsShow> piatsShows=new ArrayList<>();
    protected List<StorageInfo> storageInfoList;
    protected boolean isPick,isScrap=false;
    private int inOrOutType=-1;
    private Context context=BaseActivity.this;
    private boolean isUsable=false;
    protected List<GlobalDictionary> globalDictionaryList=null;
    protected List<RefDept> deptList2;//配送单位
    private ListView listView;
    protected PopupWindow popup;
    protected boolean isCheck=false;
    private String simpleName;
    private String[] moveReasonName = {"包装无法识别", "超过有效期", "不符合储存温度要求", "其他"};
    private String[] moveReasonId = {"01", "02", "03", "09"};
    protected RecyclerAdapter recyclerAdapter;
    private RecyclerView rvReason;

    //    private TextToSpeech _textToSpeech = null;//创建自带语音对象
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                View view = getCurrentFocus();
                UtilHelper.hideKeyboard(ev, view, BaseActivity.this);//调用方法判断是否需要隐藏键盘
                break;

            default:
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        application = (ScanApplication) getApplication();
        super.onCreate(savedInstanceState);
        simpleName=getClass().getSimpleName();
        String name=getClass().getName();
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE;
        getWindow().setAttributes(params);

//        _user = getSharedPreferences("user", MODE_PRIVATE);
//        initTTS();
//        public String getUserInfo(String key){
//        return _user.getString(key,"");
    }

    protected void initHeader(String title) {
        if ("0".equals(application.getBackSystem())) title = title + "(测试版本)";

        TextView tvTitle = ((TextView) findViewById(R.id.screenTitle));
        if (tvTitle != null) tvTitle.setText(title);
        LinearLayout ll = findViewById(R.id.llScreenUser);
        if (ll != null) {
            findViewById(R.id.btnBack).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (beforeClose()) {
                        finish();
                    }
                }
            });
            ll.setOnTouchListener(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return false;
                }
            });
            String userName = application.getRealName() == null ? application.getUserName() : application.getRealName();
            ((TextView) findViewById(R.id.tvHeaderUserName)).setText(userName);
            ll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {//返回重新登录

                }
            });
        }
        ((TextView) findViewById(R.id.tvHeaderDeptName)).setText(application.getDeptName());
    }
    protected void initHeader3(String title) {
        if ("0".equals(application.getBackSystem())) title = title + "(测试版本)";
        TextView tvTitle = ((TextView) findViewById(R.id.screenTitle));
        if (tvTitle != null) tvTitle.setText(title);
        findViewById(R.id.btnBack).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        String userName = application.getRealName() == null ? application.getUserName() : application.getRealName();
        ((TextView) findViewById(R.id.tvHeaderUserName)).setText(userName);
    }



    protected void initHeader2(String title) {
        if ("0".equals(application.getBackSystem())) title = title + "(测试版本)";

        TextView tvTitle = ((TextView) findViewById(R.id.screenTitle));
        if (tvTitle != null) tvTitle.setText(title);
        LinearLayout ll = findViewById(R.id.llScreenUser);
        if (ll != null) {
            findViewById(R.id.btnBack).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (beforeClose()) {
                        finish();
                    }
                }
            });
            ll.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return false;
                }
            });
            String userName = application.getRealName() == null ? application.getUserName() : application.getRealName();
            ((TextView) findViewById(R.id.tvHeaderUserName)).setText(userName);
            ll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {//返回重新登录

                }
            });
        }
    }

    protected boolean beforeClose() {
        //openNLDScan();
        return true;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                return super.dispatchKeyEvent(event);
            } else {//只有key_up时，才做验证。
                if (beforeClose()) return super.dispatchKeyEvent(event);
                else return false;//无论return true还是false,只要没调用 super.dispatchKeyEvent(event),就退不出去
            }
        } else {
            return super.dispatchKeyEvent(event);
        }
    }

    public void fragmentCreated(View view) {
    }
    public void fragmentCreated2(View view) {
    }

    public void alarm(String data) {
         /*设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
        _textToSpeech.setPitch(1.0f);
        // 设置语速
        _textToSpeech.setSpeechRate(0.1f);
        _textToSpeech.speak(data,//输入中文，若不支持的设备则不会读出来
                TextToSpeech.QUEUE_FLUSH, null);*/

    }
    /*获取供货单位列表*/
    protected void getDept() {
        String baseUrl = UtilHelper.baseUrls.EMIAO(application.getBackSystem());
        Retrofit retrofit = UtilHelper.retrofit(application, baseUrl);
        Map<String, String> params = ParamsMapUtil.getInstance("deptId", application.getDeptId()).addParam("pageIndex", String.valueOf(0)).addParam("pageSize", String.valueOf(1000));
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = null;
        VaccineService vs = retrofit.create(VaccineService.class);
        jsonForResultCall = vs.getContactDeptList(token, params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                        deptList = JSON.parseArray(jsonForResult.getData().toString(), RefDept.class);
                    } else {
                        if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                            UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                        }
                    }
                } catch (Exception e) {
                    Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "获取供货单位失败!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /*获取配送单位列表*/
    protected void getVaccineDistributionDempartByDeptId() {
        String baseUrl = UtilHelper.baseUrls.EMIAO(application.getBackSystem());
        Retrofit retrofit = UtilHelper.retrofit(application, baseUrl);
        Map<String, String> params = ParamsMapUtil.getInstance("deptId", application.getDeptId());
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = null;
        VaccineService vs = retrofit.create(VaccineService.class);
        jsonForResultCall = vs.getVaccineDistributionDempartByDeptId(token, params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                        deptList2 = JSON.parseArray(jsonForResult.getData().toString(), RefDept.class);
                    } else {
                        if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                            UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                        }
                    }
                } catch (Exception e) {
                    Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "获取配送单位列表失败!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private class GetDeptListCallback implements Callback<JsonForResult> {
        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                    deptList = JSON.parseArray(jsonForResult.getData().toString(), RefDept.class);
                } else {
                    if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "获取数据失败!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
        }
    }
    /*获取运输设备*/
    protected void getGlobalDictionaryByType(String type) {
        String baseUrl = UtilHelper.baseUrls.API(application.getBackSystem());
        Retrofit retrofit = UtilHelper.retrofit(application, baseUrl);
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("typeName", type);
        String token = application.getAccessToken();
        VaccineService vs = retrofit.create(VaccineService.class);
        Call<JsonForResult> jsonForResultCall = vs.getGlobalDictionaryByType(token, params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                        globalDictionaryList = JSON.parseArray(jsonForResult.getData().toString(), GlobalDictionary.class);
                    } else {
                        if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                            UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                        }
                    }
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "获取运输设备失败!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
            }
        });
    }


    /*获取盘点人或报损人*/
    protected void getPerson() {
        String baseUrl = UtilHelper.baseUrls.UC(application.getBackSystem());
        Retrofit retrofit = UtilHelper.retrofit(application, baseUrl);
        Map<String, String> params = ParamsMapUtil.getInstance("deptId", application.getDeptId()).addParam("pageIndex", String.valueOf(0)).addParam("pageSize", String.valueOf(10));
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = null;
        GetVaccineService vs = retrofit.create(GetVaccineService.class);
        jsonForResultCall = vs.getUserMstList(token, params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                        personList = JSON.parseArray((JSONObject.parseObject(jsonForResult.getData().toString())).getJSONArray("userList").toString(), Person.class);
                    } else {
                        if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                            UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                        }
                    }
                } catch (Exception e) {
                    Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "获取盘点人或报损人失败!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /*获取供货单位列表*/
    protected void getShipDepartment() {
        String baseUrl = UtilHelper.baseUrls.EMIAO(application.getBackSystem());
        Retrofit retrofit = UtilHelper.retrofit(application, baseUrl);
        Map<String, String> params = ParamsMapUtil.getInstance("deptId", application.getDeptId()).addParam("pageIndex", String.valueOf(0)).addParam("pageSize", String.valueOf(1000));
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = null;
        VaccineService vs = retrofit.create(VaccineService.class);
        jsonForResultCall = vs.getShipDepartmentList(token, params);
        jsonForResultCall.enqueue(new getShipDepartmentListCallback());
    }

    private class getShipDepartmentListCallback implements Callback<JsonForResult> {
        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                    deptList = JSON.parseArray(jsonForResult.getData().toString(), RefDept.class);
                } else {
                    if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "获取数据失败!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
        }
    }
    /*获取审核人列表*/
    protected void getApproval(TextView btnApprovalIn,String type) {
        String baseUrl = UtilHelper.baseUrls.EMIAO(application.getBackSystem());
        Retrofit retrofit = UtilHelper.retrofit(application, baseUrl);
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("deptId", application.getDeptId());
        params.put("category", type);
        String token = application.getAccessToken();
        VaccineService vs = retrofit.create(VaccineService.class);
        Call<JsonForResult> jsonForResultCall = vs.getApprovalList(token, params);
        jsonForResultCall.enqueue(new getApprovalListCallback(btnApprovalIn));
    }

    private class getApprovalListCallback implements Callback<JsonForResult> {
        private TextView btnApprovalIn;
        public getApprovalListCallback(TextView btnApprovalIn) {
            this.btnApprovalIn=btnApprovalIn;
        }

        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                    approvalList = JSON.parseArray(jsonForResult.getData().toString(), Approval.class);
                    if(btnApprovalIn!=null){
                        btnApprovalIn.setText(approvalList.get(0).getUserName1());
                        btnApprovalIn.setTextColor(btnApprovalIn.getResources().getColor(R.color.billTextChoose));
                        application.setApprovalId(approvalList.get(0).getId());
                    }
                } else {
                    if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "获取数据失败!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
        }
    }
    /*获取价格本列表*/
    protected void getPriceBookMst() {
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("deptId", application.getDeptId());
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.EMIAO(application.getBackSystem()));
        VaccineService vs = retrofit.create(VaccineService.class);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = vs.getPriceBookMstList(token, params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    if (response.code() != 200) {
                        UtilHelper.alertMsg(context, "错误", response.code() + response.message());
                        return;
                    }
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        priceBook = JSON.parseArray(jsonForResult.getData().toString(), PriceBook.class);
                    } else {
                        if (jsonForResult != null) {
                            UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                        }
                    }
                } catch (Exception e) {
                    Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }


    /*获取储位列表*/
    protected void getStorageInfoList() {
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("deptId", application.getDeptId());
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.EMIAO(application.getBackSystem()));
        VaccineService vs = retrofit.create(VaccineService.class);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = vs.getStorageInfoList(token, params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                        storageInfoList = JSON.parseArray(jsonForResult.getData().toString(), StorageInfo.class);
                    } else {
                        if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                            UtilHelper.alertMsg(getParent(), "错误", jsonForResult.getMessage());
                        }
                    }
                } catch (Exception e) {
                    Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    /*获取储位列表*/
    protected void getStorageInfoByDept(String type) {
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("deptId", application.getDeptId());
        params.put("type",type);
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.EMIAO(application.getBackSystem()));
        VaccineService vs = retrofit.create(VaccineService.class);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = vs.getStorageInfoByDept(token, params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                        storageInfoList = JSON.parseArray(jsonForResult.getData().toString(), StorageInfo.class);
                    } else {
                        if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                            UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                        }
                    }
                } catch (Exception e) {
                    Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }



    protected void getVaccineInfoByCodeSingle(String code,String index,int inOrOut,RecyclerView recyclerView) {
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("deptId", application.getDeptId());
        params.put("code", code);
        params.put("orderType", String.valueOf(inOrOut));
        inOrOutType=inOrOut;
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API(application.getBackSystem()));
        VaccineService vs = retrofit.create(VaccineService.class);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = vs.getVaccineInfoByCodeSingle(token, params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {

                try {
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if (jsonForResult.getData() == null) {
                            UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                            return;
                        }
                        //请求授权信息
                        List<PiatsInfo> piatsInfoList = JSON.parseArray(jsonForResult.getData().toString(), PiatsInfo.class);
                        if (CollectionUtil.isNullOrEmpty(piatsInfoList)) {
                            UtilHelper.alertMsg(context, "错误", "获取疫苗信息失败");
                            return;
                        }
                        PiatsInfo piatsInfo = piatsInfoList.get(0);
                        if(index.equals("4")){
                            if(inOrOut==13){//调拨入库
                                checkVaccineStatus(piatsInfo,recyclerView);
                            }else {
                                piatsInfo.setStorageName(application.getStorageName());
                                piatsInfo.setStorageId(application.getStorageId());
                                if (!application.getCategory().equals(piatsInfo.getCategory())) {
                                    Toast.makeText(BaseActivity.this, "扫描疫苗类型不符合!", Toast.LENGTH_SHORT).show();
                                } else {
                                    if (simpleName.equals("GiftInActivity") && !piatsInfo.getProduceMappingId().equals(application.getRefDeptId())) {
                                        Toast.makeText(BaseActivity.this, "选择的发货单位与该码的生产厂家不一致!", Toast.LENGTH_SHORT).show();
                                    } else {
                                        /*因为可能会*/
                                        boolean isContain = false;
                                        for (PiatsInfo info : piatsInfos) {
                                            if (info.getCode().equals(piatsInfo.getCode())) {
                                                isContain = true;
                                                break;
                                            }
                                        }
                                        if (isContain == false) {
                                            piatsInfo.setWriteQuality(piatsInfo.getPkgAmount());
                                            piatsInfos.add(piatsInfo);
                                            if (recyclerAdapter == null) {
                                                recyclerAdapter = new RecyclerAdapter(piatsInfos);
                                                recyclerView.setAdapter(recyclerAdapter);
                                            } else {
                                                recyclerAdapter.notifyItemInserted(piatsInfos.size() - 1);
                                                recyclerAdapter.notifyItemRangeChanged(piatsInfos.size() - 1, 1);//更新的位置,更新的总条数
                                            }
                                            if (simpleName.equals("ScrapOutActivity") || simpleName.equals("RuinOutActivity")) {
                                                dialogShow(piatsInfos.get(piatsInfos.size() - 1), piatsInfos.size() - 1);
                                                ScanUtil.powerOffScan(context);
                                            } else if (simpleName.equals("GiftInActivity")) {
                                                dialogInShow(piatsInfos.get(piatsInfos.size() - 1), piatsInfos.size() - 1);
                                            } else {
                                                dialogShow(piatsInfos.get(piatsInfos.size() - 1), piatsInfos.size() - 1);
                                            }
                                /*if(inOrOutType==1){
                                    TextDialog.showDialog(BaseActivity.this,piatsInfos,recyclerAdapter);
                                }*/
                                        } else {
                                            Toast.makeText(context, "该疫苗已经扫描", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                }
                            }
                        }else{
                            if (piatsInfo.getStorageScanVoList().size() != 0) {
                                piatsInfo.setStorageName(piatsInfo.getStorageScanVoList().get(0).getStorage());
                                piatsInfo.setStorageId(piatsInfo.getStorageScanVoList().get(0).getStorageId());
                                if(!VaccineContain.isContain(piatsInfos,piatsInfo)){
                                    piatsInfo.setWriteQuality(piatsInfo.getPkgAmount());
                                    piatsInfos.add(piatsInfo);
                                    if (piatsInfos.size() == 1) {
                                        recyclerAdapter = new RecyclerAdapter(piatsInfos);
                                        recyclerView.setAdapter(recyclerAdapter);
                                    } else {
                                        recyclerAdapter.notifyItemInserted(piatsInfos.size()-1);
                                        recyclerAdapter.notifyItemRangeChanged(piatsInfos.size()-1, 1);//更新的位置,更新的总条数
                                    }
                                    if(_alertDialog!=null){
                                        _alertDialog.dismiss();
                                    }
                                    dialogShow(piatsInfos.get(piatsInfos.size()-1), piatsInfos.size()-1);
                                }else{
                                    Toast.makeText(context, "该疫苗已经扫描", Toast.LENGTH_SHORT).show();
                                }

                            } else {
                                Toast.makeText(context, "该疫苗没有库存", Toast.LENGTH_SHORT).show();
                            }
                        }

                    }else if(jsonForResult != null &&(!jsonForResult.isSuccess())){
                        Toast.makeText(context,jsonForResult.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });//根据index来判断储位要不要从新选择
    }

    private void checkVaccineStatus(PiatsInfo piatsInfo,RecyclerView recyclerView){
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("propertyId", piatsInfo.getPropertyId());
        params.put("batchId", piatsInfo.getBatchId());
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.EMIAO(application.getBackSystem()));
        GetVaccineService vs = retrofit.create(GetVaccineService.class);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = vs.checkVaccineStatus(token, params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null) {
                        if(jsonForResult.isSuccess()){
                            piatsInfo.setStorageName(application.getStorageName());
                                piatsInfo.setStorageId(application.getStorageId());
                                if (!application.getCategory().equals(piatsInfo.getCategory())) {
                                    Toast.makeText(BaseActivity.this, "扫描疫苗类型不符合!", Toast.LENGTH_SHORT).show();
                                } else {
                                    /*因为可能会*/
                                    boolean isContain = false;
                                    for (PiatsInfo info : piatsInfos) {
                                        if (info.getCode().equals(piatsInfo.getCode())) {
                                            isContain = true;
                                            break;
                                        }
                                    }
                                    if (isContain == false) {
                                        piatsInfo.setWriteQuality(piatsInfo.getPkgAmount());
                                        piatsInfos.add(piatsInfo);
                                        if (recyclerAdapter == null) {
                                            recyclerAdapter = new RecyclerAdapter(piatsInfos);
                                            recyclerView.setAdapter(recyclerAdapter);
                                        } else {
                                            recyclerAdapter.notifyItemInserted(piatsInfos.size() - 1);
                                            recyclerAdapter.notifyItemRangeChanged(piatsInfos.size() - 1, 1);//更新的位置,更新的总条数
                                        }
                                        if (simpleName.equals("ScrapOutActivity") || simpleName.equals("RuinOutActivity")) {
                                            dialogShow(piatsInfos.get(piatsInfos.size() - 1), piatsInfos.size() - 1);
                                            ScanUtil.powerOffScan(context);
                                        } else if (simpleName.equals("GiftInActivity")) {
                                            dialogInShow(piatsInfos.get(piatsInfos.size() - 1), piatsInfos.size() - 1);
                                        } else {
                                            dialogShow(piatsInfos.get(piatsInfos.size() - 1), piatsInfos.size() - 1);
                                        }
                                    } else {
                                        Toast.makeText(context, "该疫苗已经扫描", Toast.LENGTH_SHORT).show();
                                    }
                                }
                        }
                        if(!jsonForResult.isSuccess()&&!StringUtil.isNullOrEmpty(jsonForResult.getMessage())){
                            Toast.makeText(context,jsonForResult.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                Toast.makeText(context,msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /*供应入库为了获取字段contractNoList*/
    protected void getVaccineInfoByCodeSingle(String code) {
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("deptId", application.getDeptId());
        params.put("code", code);
        params.put("orderType","2");
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API(application.getBackSystem()));
        VaccineService vs = retrofit.create(VaccineService.class);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = vs.getVaccineInfoByCodeSingle(token, params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {

                try {
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if (jsonForResult.getData() == null) {
                            UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                            return;
                        }
                        //请求授权信息
                        List<PiatsInfo> piatsInfoList = JSON.parseArray(jsonForResult.getData().toString(), PiatsInfo.class);
                        if (CollectionUtil.isNullOrEmpty(piatsInfoList)) {
                            UtilHelper.alertMsg(context, "错误", "获取疫苗信息失败");
                            return;
                        }
                        PiatsInfo piatsInfo = piatsInfoList.get(0);
                        if(piatsInfo.getContractNoList()!=null) {
                            application.setContractNo(piatsInfo.getContractNoList().get(0));
                        }else{
                            application.setContractNo(null);
                        }

                    }else if(jsonForResult != null &&(!jsonForResult.isSuccess())){
                        Toast.makeText(context,jsonForResult.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });//根据index来判断储位要不要从新选择
    }

    protected boolean getVaccineIsUsable(String code,int inOrOut) {
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("deptId", application.getDeptId());
        params.put("code", code);
        params.put("orderType", String.valueOf(inOrOut));
        inOrOutType=inOrOut;
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API(application.getBackSystem()));
        VaccineService vs = retrofit.create(VaccineService.class);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = vs.getVaccineInfoByCodeSingle(token, params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {

                try {
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        isUsable=true;
                    }else if(jsonForResult != null &&(!jsonForResult.isSuccess())){
                        Toast.makeText(context,jsonForResult.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });//根据index来判断储位要不要从新选择
        return isUsable;
    }


    public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
        private List<PiatsInfo> piatsInfos;

        public RecyclerAdapter(List<PiatsInfo> piatsInfos) {
            this.piatsInfos = piatsInfos;
        }

        @NonNull
        @Override
        public RecyclerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_vaccine_attribute, parent, false);
            RecyclerAdapter.ViewHolder viewHolder = new RecyclerAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerAdapter.ViewHolder holder, int position) {
            holder.tv_electCode.setText(piatsInfos.get(position).getCode());
            holder.tvVaccineName.setText(piatsInfos.get(position).getPhysicName());
            holder.tvFactory.setText(piatsInfos.get(position).getProduceName());
            holder.tvApprovalNo.setText(piatsInfos.get(position).getApproveNo());
            holder.tvVaccineDose.setText(piatsInfos.get(position).getPrepnSpec() + "/" + piatsInfos.get(position).getPkgSpec());
            holder.tvCodeLevelStr.setText(piatsInfos.get(position).getCodeLevelStr());
            if(piatsInfos.get(position).getExpireDate()!=null){
                if(piatsInfos.get(position).getExpireDate().contains("-")){
                    holder.tvExpireDate.setText(piatsInfos.get(position).getExpireDate().substring(0,10));
                }else {
                    holder.tvExpireDate.setText(piatsInfos.get(position).getExpireDate().substring(0,8));
                }
            }
            holder.tvUnitPrice.setText(String.valueOf(piatsInfos.get(position).getUnitPrice()));
            holder.tvQuantity.setText(String.valueOf(piatsInfos.get(position).getPkgAmount()));
            holder.tvServicePrice.setText(String.valueOf(Integer.valueOf(piatsInfos.get(position).getPkgAmount()) * piatsInfos.get(position).getUnitPrice()));
            if (piatsInfos.get(position).getStorageName() == null) {
                holder.tvStorage.setText(application.getStorageName());
            } else {
                holder.tvStorage.setText(piatsInfos.get(position).getStorageName());
            }
            if (piatsInfos.get(position).getCategory().equals("1")) {
                holder.iv_category.setText("免规");
            }else if(piatsInfos.get(position).getCategory().equals("4")){
                holder.iv_category.setText("地方免规");
            }else if(piatsInfos.get(position).getCategory().equals("5")){
                holder.iv_category.setText("应急");
            }else if(piatsInfos.get(position).getCategory().equals("2")){
                holder.iv_category.setText("非免规");
            }else if(piatsInfos.get(position).getCategory().equals("6")){
                holder.iv_category.setText("群体性预防");
            }else if(piatsInfos.get(position).getCategory().equals("7")){
                holder.iv_category.setText("紧急");
            }
            if("ScrapInActivity".equals(simpleName)||"ScrapOutActivity".equals(simpleName)||"RuinOutActivity".equals(simpleName)){
                holder.lin_reason.setVisibility(View.VISIBLE);
                if("9".equals(piatsInfos.get(position).getReason())){
                    holder.tvReason.setText(application.getReason(piatsInfos.get(position).getReason())+piatsInfos.get(position).getOtherReason());
                }else{
                    holder.tvReason.setText(application.getReason(piatsInfos.get(position).getReason()));
                }
            }
            holder.iv_del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    piatsInfos.remove(position);
                    notifyItemRemoved(position);//移除该位置的项目
                    notifyItemRangeChanged(position, getItemCount() - position);//局部刷新从该position位置开始到剩余的所有项目
                }
            });
            //跳弹窗,选择储位
            holder.linStorage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if("ReturnInActivity".equals(simpleName)||"ScrapInActivity".equals(simpleName)||"AllotInActivity".equals(simpleName)||"RecallInActivity".equals(simpleName)){
                        dialogInShow(piatsInfos.get(position), position);
                    }else {
                        dialogShow(piatsInfos.get(position), position);
                    }
                }
            });
            //跳弹窗,选择储位
            holder.lin_reason.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String dd=getClass().getSimpleName();
                    if("ScrapInActivity".equals(simpleName)||"ScrapOutActivity".equals(simpleName)||"RuinOutActivity".equals(simpleName)){
                        dialogReasonShow(piatsInfos.get(position), position);
                    }
                }
            });
            holder.lin_number.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(inOrOutType==4){//退货出库，可以改数量
                         TextDialog.showDialog(BaseActivity.this,piatsInfos,position,holder.tvQuantity);
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return piatsInfos.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_electCode, tvVaccineName, tvFactory, tvApprovalNo,iv_category,tvReason; //追溯码,疫苗名称，生产厂家，批号,疫苗属性
            TextView tvVaccineDose, tvCodeLevelStr, tvExpireDate, tvUnitPrice, tvQuantity, tvServicePrice, tvStorage; // 计量规格,包装类型,效期,单价,数量,金额,储位
            ImageView iv_del;
            LinearLayout linStorage,lin_number,lin_vaccine,lin_reason;

            public ViewHolder(View itemView) {
                super(itemView);
                this.tv_electCode = itemView.findViewById(R.id.tv_electCode);
                this.tvVaccineName = itemView.findViewById(R.id.tvVaccineName);
                this.tvReason = itemView.findViewById(R.id.tvReason);
                this.iv_del = itemView.findViewById(R.id.iv_del);
                this.iv_category = itemView.findViewById(R.id.iv_category);
                this.tvFactory = itemView.findViewById(R.id.tvFactory);
                this.tvApprovalNo = itemView.findViewById(R.id.tvApprovalNo);
                this.tvVaccineDose = itemView.findViewById(R.id.tvVaccineDose);
                this.tvCodeLevelStr = itemView.findViewById(R.id.tvCodeLevelStr);
                this.tvExpireDate = itemView.findViewById(R.id.tvExpireDate);
                this.tvUnitPrice = itemView.findViewById(R.id.tvUnitPrice);
                this.tvQuantity = itemView.findViewById(R.id.tvQuantity);
                this.tvServicePrice = itemView.findViewById(R.id.tvServicePrice);
                this.tvStorage = itemView.findViewById(R.id.tvStorage);
                this.linStorage = itemView.findViewById(R.id.linStorage);
                this.lin_number = itemView.findViewById(R.id.lin_number);
                this.lin_vaccine = itemView.findViewById(R.id.lin_vaccine);
                this.lin_reason = itemView.findViewById(R.id.lin_reason);
            }
        }
    }

    public void  dialogStorageReasonShow(PiatsInfo piatsInfo, int position) {
        LayoutInflater mLayoutInflater = LayoutInflater.from(this);
        View view = mLayoutInflater.inflate(R.layout.dialog_choose_storage_and_reason, null);
        final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setView(view);
        _alertDialog = alertBuilder.create();
        _alertDialog.show();
        btnStorage = (Button) view.findViewById(R.id.btnStorage);
        TextView tvCancel = (TextView) view.findViewById(R.id.tvCancel);
        TextView tvConfirm = (TextView) view.findViewById(R.id.tvConfirm);
        TextView btnReason = (TextView) view.findViewById(R.id.btnReason);
        EditText btnReason2 = (EditText) view.findViewById(R.id.btnReason2);
        linearLayout = (LinearLayout) view.findViewById(R.id.linearLayout2);
        rvStorage = (RecyclerView) view.findViewById(R.id.rvStorage);
        rvReason = (RecyclerView) view.findViewById(R.id.rvReason);
        if(piatsInfo.getStorageScanVoList()!=null&&piatsInfo.getStorageScanVoList().size()>0) {
            btnStorage.setText(piatsInfo.getStorageScanVoList().get(0).getStorage());//默认是选中第一个储位,记得把储位的id留着
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        rvStorage.setLayoutManager(layoutManager);
        LinearLayoutManager layoutManager2 = new LinearLayoutManager(context);
        rvReason.setLayoutManager(layoutManager);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ScanUtil.powerOnScan(context);
                _alertDialog.dismiss();
            }
        });
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ScanUtil.powerOnScan(context);
                _alertDialog.dismiss();
                PiatsInfo piatsInfo1 = piatsInfos.get(position);
                List<StorageChoose> storageChooseList = piatsInfo1.getStorageScanVoList();
                for (int i = 0; i < storageChooseList.size(); i++) {
                    if (storageChooseList.get(i).getStorage().equals(btnStorage.getText().toString())) {
                        piatsInfo1.setStorageName(storageChooseList.get(i).getStorage());
                        piatsInfo1.setStorageId(storageChooseList.get(i).getStorageId());
                        break;
                    }
                }
                if(btnReason.getText().toString().trim().equals("包装无法识别")){
                    piatsInfo.setReason("01");piatsInfo.setOtherReason("");
                }else if(btnReason.getText().toString().trim().equals("超过有效期")){
                    piatsInfo.setReason("02");piatsInfo.setOtherReason("");
                }else if(btnReason.getText().toString().trim().equals("不符合储存温度要求")){
                    piatsInfo.setReason("03");piatsInfo.setOtherReason("");
                }else if(btnReason.getText().toString().trim().equals("其他")){
                    piatsInfo.setReason("09");piatsInfo.setOtherReason(btnReason2.getText().toString());
                }
                recyclerAdapter.notifyItemRangeChanged(position, 1);//更新的位置,更新的总条数
            }
        });
        btnStorage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rvStorage.setVisibility(View.VISIBLE);
                StorageAdapter storageAdapter = new StorageAdapter( piatsInfo.getStorageScanVoList());
                rvStorage.setAdapter(storageAdapter);
            }
        });
        btnReason.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rvReason.setVisibility(View.VISIBLE);
                ReasonAdapter storageAdapter = new ReasonAdapter(rvReason,btnReason,btnReason2, Arrays.asList(moveReasonName), Arrays.asList(moveReasonId));
                rvStorage.setAdapter(storageAdapter);
            }
        });

    }

    public void  dialogShow(PiatsInfo piatsInfo, int position) {
        LayoutInflater mLayoutInflater = LayoutInflater.from(this);
        View view = mLayoutInflater.inflate(R.layout.dialog_choose_storage, null);
        final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setView(view);
        _alertDialog = alertBuilder.create();
        _alertDialog.show();
        btnStorage = (Button) view.findViewById(R.id.btnStorage);
        TextView tvCancel = (TextView) view.findViewById(R.id.tvCancel);
        TextView tvConfirm = (TextView) view.findViewById(R.id.tvConfirm);
        linearLayout = (LinearLayout) view.findViewById(R.id.linearLayout2);
        rvStorage = (RecyclerView) view.findViewById(R.id.rvStorage);
        List<StorageChoose> storageChooseList = piatsInfo.getStorageScanVoList();
        if(storageChooseList!=null&&storageChooseList.size()!=0)btnStorage.setText(piatsInfo.getStorageScanVoList().get(0).getStorage());//默认是选中第一个储位,记得把储位的id留着
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        rvStorage.setLayoutManager(layoutManager);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                _alertDialog.dismiss();
                ScanUtil.powerOnScan(context);
            }
        });
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                _alertDialog.dismiss();
                ScanUtil.powerOnScan(context);
                PiatsInfo piatsInfo1 = piatsInfos.get(position);
                List<StorageChoose> storageChooseList = piatsInfo1.getStorageScanVoList();
                if(storageChooseList!=null&&storageChooseList.size()!=0) {
                    for (int i = 0; i < storageChooseList.size(); i++) {
                        if (storageChooseList.get(i).getStorage().equals(btnStorage.getText().toString())) {
                            piatsInfo1.setStorageName(storageChooseList.get(i).getStorage());
                            piatsInfo1.setStorageId(storageChooseList.get(i).getStorageId());
                            break;
                        }
                    }
                    recyclerAdapter.notifyItemRangeChanged(position, 1);//更新的位置,更新的总条数
                }
            }
        });
        btnStorage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rvStorage.setVisibility(View.VISIBLE);
                linearLayout.setVisibility(View.INVISIBLE);
                List<StorageChoose> storageChooseList = piatsInfo.getStorageScanVoList();
                if(storageChooseList!=null&&storageChooseList.size()!=0) {
                    StorageAdapter storageAdapter = new StorageAdapter(piatsInfo.getStorageScanVoList());
                    rvStorage.setAdapter(storageAdapter);
                }else{
                    Toast.makeText(context,"没有库存",Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    public void dialogInShow(PiatsInfo piatsInfo, int position) {
        LayoutInflater mLayoutInflater = LayoutInflater.from(this);
        View view = mLayoutInflater.inflate(R.layout.dialog_choose_storage, null);
        final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setView(view);
        _alertDialog = alertBuilder.create();
        _alertDialog.show();
        btnStorage = (Button) view.findViewById(R.id.btnStorage);
        TextView tvCancel = (TextView) view.findViewById(R.id.tvCancel);
        TextView tvConfirm = (TextView) view.findViewById(R.id.tvConfirm);
        linearLayout = (LinearLayout) view.findViewById(R.id.linearLayout2);
        rvStorage = (RecyclerView) view.findViewById(R.id.rvStorage);
        btnStorage.setText(storageInfoList.get(0).getName());//默认是选中第一个储位,记得把储位的id留着
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        rvStorage.setLayoutManager(layoutManager);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                _alertDialog.dismiss();
            }
        });
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                _alertDialog.dismiss();
                PiatsInfo piatsInfo1 = piatsInfos.get(position);
                if(storageInfoList!=null) {
                    for (int i = 0; i < storageInfoList.size(); i++) {
                        if (storageInfoList.get(i).getName().equals(btnStorage.getText().toString())) {
                            piatsInfo1.setStorageName(storageInfoList.get(i).getName());
                            piatsInfo1.setStorageId(storageInfoList.get(i).getId());
                            break;
                        }
                    }
                }
                recyclerAdapter.notifyItemRangeChanged(position, 1);//更新的位置,更新的总条数
            }
        });
        btnStorage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rvStorage.setVisibility(View.VISIBLE);
                linearLayout.setVisibility(View.INVISIBLE);

                StorageInAdapter storageAdapter = new StorageInAdapter(storageInfoList);
                rvStorage.setAdapter(storageAdapter);
            }
        });

    }
    public class StorageInAdapter extends RecyclerView.Adapter<StorageInAdapter.ViewHolder> {
        private List<StorageInfo> storageList;

        public StorageInAdapter(List<StorageInfo> storageList) {
            this.storageList = storageList;
        }

        @NonNull
        @Override
        public StorageInAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_dialog_storage, parent, false);
            StorageInAdapter.ViewHolder viewHolder = new StorageInAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull StorageInAdapter.ViewHolder holder, int position) {
            holder.tvStorage.setText(storageList.get(position).getName());
            holder.tvQuanlity.setVisibility(View.GONE);
            holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnStorage.setText(storageList.get(position).getName());
                    rvStorage.setVisibility(View.GONE);
                    linearLayout.setVisibility(View.VISIBLE);
                }
            });
        }

        @Override
        public int getItemCount() {
            System.out.println("储位数量" + storageList.size());
            return storageList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tvStorage,tvQuanlity;
            RelativeLayout relativeLayout;

            public ViewHolder(View itemView) {
                super(itemView);
                this.tvStorage = itemView.findViewById(R.id.tvStorage);
                this.tvQuanlity = itemView.findViewById(R.id.tvQuanlity);
                this.relativeLayout = itemView.findViewById(R.id.relativeLayout);
            }
        }
    }
    public class StorageAdapter extends RecyclerView.Adapter<StorageAdapter.ViewHolder> {
        private List<StorageChoose> storageList;

        public StorageAdapter(List<StorageChoose> storageList) {
            this.storageList = storageList;
        }

        @NonNull
        @Override
        public StorageAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_dialog_storage, parent, false);
            StorageAdapter.ViewHolder viewHolder = new StorageAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull StorageAdapter.ViewHolder holder, int position) {
            holder.tvStorage.setText(storageList.get(position).getStorage());
            holder.tvQuanlity.setText("库存:"+(StringUtil.isNullOrEmpty(storageList.get(position).getQuantity())?0:storageList.get(position).getQuantity()));
            holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnStorage.setText(storageList.get(position).getStorage());
                    rvStorage.setVisibility(View.GONE);
                    linearLayout.setVisibility(View.VISIBLE);
                }
            });
        }

        @Override
        public int getItemCount() {
            System.out.println("储位数量" + storageList.size());
            return storageList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tvStorage,tvQuanlity;
            RelativeLayout relativeLayout;

            public ViewHolder(View itemView) {
                super(itemView);
                this.tvStorage = itemView.findViewById(R.id.tvStorage);
                this.tvQuanlity = itemView.findViewById(R.id.tvQuanlity);
                this.relativeLayout = itemView.findViewById(R.id.relativeLayout);
            }
        }
    }

    public void showDetail(RecyclerView recyclerView,TextView tv_total,String isOut){
        if(piatsInfos.size()>0){
            int totalNum=0;
            for (PiatsInfo piatsInfo : piatsInfos) {
                PiatsShow piatsShow=new PiatsShow();
                piatsShow.setStorage(piatsInfo.getStorageName());
                piatsShow.setVaccineId(piatsInfo.getMappingId());
                piatsShow.setVaccineName(piatsInfo.getPhysicName());
                piatsShow.setLotNumber(piatsInfo.getBatchNo());
                if(!piatsShows.contains(piatsShow)){
                    piatsShows.add(piatsShow);
                }
                if("1".equals(isOut)){
                    totalNum=totalNum+Integer.valueOf(piatsInfo.getWriteQuality());
                }else{
                    totalNum=totalNum+Integer.valueOf(piatsInfo.getPkgAmount());
                }
            }
            tv_total.setText(String.valueOf(totalNum));
            for (PiatsShow piatsShow : piatsShows) {
                int num=0;
                for (PiatsInfo piatsInfo : piatsInfos) {
                    if(piatsShow.getStorage().equals(piatsInfo.getStorageName())&&piatsShow.getVaccineId().equals(piatsInfo.getMappingId())&&piatsShow.getLotNumber().equals(piatsInfo.getBatchNo())){
                        if("1".equals(isOut)){
                            num=num+Integer.valueOf(piatsInfo.getWriteQuality());
                        }else{
                            num=num+Integer.valueOf(piatsInfo.getPkgAmount());
                        }
                    }
                }
                piatsShow.setNum(num);
            }

            detailAdapter=new DetailAdapter(piatsShows);
            recyclerView.setAdapter(detailAdapter);
        }
    }
    public class DetailAdapter extends RecyclerView.Adapter<DetailAdapter.ViewHolder>{
        private List<PiatsShow> piatsShows;

        public DetailAdapter(List<PiatsShow> piatsShows) {
            this.piatsShows = piatsShows;
        }

        @NonNull
        @Override
        public DetailAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_scan_detail_0, parent, false);
            DetailAdapter.ViewHolder viewHolder = new DetailAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull DetailAdapter.ViewHolder holder, int position) {
            holder.tvVaccineName.setText(piatsShows.get(position).getVaccineName());
            holder.tvScanNo.setText(String.valueOf(piatsShows.get(position).getNum()));
            holder.tvLotNumber.setText(String.valueOf(piatsShows.get(position).getLotNumber()));
            holder.tvStorage.setText(String.valueOf(piatsShows.get(position).getStorage()));
//
        }

        @Override
        public int getItemCount() {
            return piatsShows.size();
        }


        class ViewHolder extends RecyclerView.ViewHolder{
            TextView tvVaccineName,tvScanNo,tvLotNumber,tvStorage; //疫苗名称，扫码数
            public ViewHolder(View itemView) {
                super(itemView);
                this.tvVaccineName = itemView.findViewById(R.id.tvVaccineName);
                this.tvScanNo = itemView.findViewById(R.id.tvScanNo);
                this.tvStorage = itemView.findViewById(R.id.tvStorage);
                this.tvLotNumber = itemView.findViewById(R.id.tvLotNumber);
            }

        }
    }
    protected void checkAllPickOrderByCondition() {
        String baseUrl = UtilHelper.baseUrls.EMIAO(application.getBackSystem());
        Retrofit retrofit = UtilHelper.retrofit(application, baseUrl);
        Map<String, String> params = ParamsMapUtil.getInstance("deptId", application.getDeptId());
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = null;
        GetVaccineService vs = retrofit.create(GetVaccineService.class);
        jsonForResultCall = vs.checkAllPickOrderByCondition(token, params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        isPick=true;
                    } else {
                        if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                            UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                        }
                    }
                } catch (Exception e) {
                    Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "获取数据失败!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    protected void checkAllScrapOrderByCondition() {
        String baseUrl = UtilHelper.baseUrls.EMIAO(application.getBackSystem());
        Retrofit retrofit = UtilHelper.retrofit(application, baseUrl);
        Map<String, String> params = ParamsMapUtil.getInstance("deptId", application.getDeptId());
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = null;
        GetVaccineService vs = retrofit.create(GetVaccineService.class);
        jsonForResultCall = vs.checkAllScrapOrderByCondition(token, params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        isScrap=true;
                    } else {
                        if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                            UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                        }
                    }
                } catch (Exception e) {
                    Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "获取数据失败!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    protected void getApprovalList(String category) {
        String baseUrl = UtilHelper.baseUrls.EMIAO(application.getBackSystem());
        Retrofit retrofit = UtilHelper.retrofit(application, baseUrl);
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("deptId", application.getDeptId());
        params.put("category", category);
        String token = application.getAccessToken();
        VaccineService vs = retrofit.create(VaccineService.class);
        Call<JsonForResult> jsonForResultCall = vs.getApprovalList(token, params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                        approvalList = JSON.parseArray(jsonForResult.getData().toString(), Approval.class);
                    } else {
                        if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                            UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                        }
                    }
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "获取数据失败!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
            }
        });
    }
    protected void getTimeDialog(View view, int i) {

        TimePickerView timePickerView = new TimePickerView.Builder(view.getContext(), new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                String start = getTime(date);
                ((TextView) view).setText(start);
                ((TextView) view).setTextColor(getResources().getColor(R.color.billTextChoose));
                if (i == 0) {
                    application.setRunTime(start);
                } else if (i == 1) {
                    application.setArrivalTime(start);
                }

            }
        }).setType(new boolean[]{true, true, true, true, true, true})
                .setCancelColor(getResources().getColor(R.color.colorCyan300))
                .setSubmitColor(getResources().getColor(R.color.colorCyan500)).build();
        //注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        timePickerView.setDate(Calendar.getInstance());
        timePickerView.show();
    }

    protected void getTimeDialog(View view) {

        TimePickerView timePickerView = new TimePickerView.Builder(view.getContext(), new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                String start = getTime(date);
                ((TextView) view).setText(start);
                ((TextView) view).setTextColor(getResources().getColor(R.color.billTextChoose));
            }
        }).isDialog(true).setType(new boolean[]{true, true, true, true, true, true})
                .setCancelColor(getResources().getColor(R.color.colorCyan300))
                .setSubmitColor(getResources().getColor(R.color.colorCyan500)).build();
        //注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        timePickerView.setDate(Calendar.getInstance());
        timePickerView.show();
    }
    protected String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }
    public static Date getDate(String view) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//注意月份是MM
        Date date = null;
        try {
            date = simpleDateFormat.parse(view);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /*选择单号下拉框*/
    protected void show(TextView textView,TextView btnSupplyDept,TextView btnVaccineType,TextView btnStartTime,TextView btnEndTime,TextView btnDeliveryDept,List<String> createTime,List<String> name, List<String> id, List<String> deptId, List<String> category, List<String> sourceId, List<String> transformUnit, List<String> transformUnitName) {
        listView = new ListView(context);
        listView.setDivider(null);//设置分割线
        listView.setVerticalScrollBarEnabled(false);//不显示滑动条
        listView.setAdapter(new MyAdapter(textView,btnSupplyDept,btnVaccineType,btnStartTime,btnEndTime,btnDeliveryDept,createTime,name, id, deptId, category,sourceId,transformUnit,transformUnitName));
        createPopupWindow(textView);
        textView.setBackgroundResource(R.drawable.selector_focused);
        popup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                textView.setBackgroundResource(R.drawable.selector_unfocused);
            }
        });
    }

    protected void createPopupWindow(TextView textView){
        popup = new PopupWindow(context);
        popup.setWidth(textView.getWidth());
        popup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.selector_unfocused));
        popup.setContentView(listView);//设置显示内容
        popup.setOutsideTouchable(true);//点击PopupWindow以外的区域自动关闭该窗口
        popup.showAsDropDown(textView, 0, 5);//显示在edit控件的下面0,0代表偏移量
    }

    //适配器
    private class MyAdapter extends BaseAdapter {
        private List<String> name, id, deptId, category, sourceId;
        private TextView textView;TextView btnSupplyDept;TextView btnVaccineType;TextView btnStartTime;TextView btnDeliveryDept;
        TextView btnEndTime;List<String> createTime; List<String> transformUnit;List<String> transformUnitName;

        public MyAdapter(TextView textView,TextView btnSupplyDept,TextView btnVaccineType,TextView btnStartTime,TextView btnEndTime,TextView btnDeliveryDept,List<String> createTime, List<String> name, List<String> id, List<String> deptId, List<String> category, List<String> sourceId,List<String> transformUnit, List<String> transformUnitName) {
            this.name = name;
            this.id = id;
            this.deptId = deptId;
            this.createTime = createTime;
            this.sourceId = sourceId;
            this.category = category;
            this.textView = textView;
            this.btnSupplyDept = btnSupplyDept;
            this.btnVaccineType = btnVaccineType;
            this.btnStartTime = btnStartTime;
            this.btnEndTime = btnEndTime;
            this.btnDeliveryDept = btnDeliveryDept;
            this.transformUnit = transformUnit;
            this.transformUnitName = transformUnitName;
        }

        @Override
        public int getCount() {
            return name.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            HolderView holderView = null;
            if (convertView == null) {
                convertView = View.inflate(context, R.layout.item_dialog_login, null);
                holderView = new HolderView();
                holderView.text = (TextView) convertView.findViewById(R.id.tvStorage);
                convertView.setTag(holderView);
            } else {
                holderView = (HolderView) convertView.getTag();
            }

            if (textView.getText().toString().equals(name.get(position))) {
                holderView.text.setTextColor(getResources().getColor(R.color.billChoosed));
            } else {
                holderView.text.setTextColor(getResources().getColor(R.color.billTextChoose));
            }
            holderView.text.setText(name.get(position));
            holderView.text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    textView.setText(name.get(position));
                    textView.setTextColor(getResources().getColor(R.color.billTextChoose));
                    application.setOrderNoId(id.get(position));
                    application.setOrderNoName(name.get(position));
                    textView.setBackgroundResource(R.drawable.selector_unfocused);
                    btnSupplyDept.setTextColor(getResources().getColor(R.color.billTextChoose));
                    btnVaccineType.setTextColor(getResources().getColor(R.color.billTextChoose));
                    btnStartTime.setTextColor(getResources().getColor(R.color.billTextChoose));
                    btnEndTime.setTextColor(getResources().getColor(R.color.billTextChoose));
                    btnEndTime.setText(getTime(new Date()));
                    btnStartTime.setText(createTime.get(position));
                    if(!StringUtil.isNullOrEmpty(transformUnit.get(position))&&!StringUtil.isNullOrEmpty(transformUnitName.get(position))){
                        application.setTransformId(transformUnit.get(position));
                        application.setTransformName(transformUnitName.get(position));
                        btnDeliveryDept.setText(transformUnitName.get(position));
                    }else{
                        application.setTransformId(null);
                        application.setTransformName(null);
                        btnDeliveryDept.setText("");
                    }

                    for (int m = 0; m < deptList.size(); m++) {
                        if (deptList.get(m).getRefDeptId().equals(deptId.get(position))) {
                            isCheck=true;
                            application.setSupplyDeptName(deptList.get(m).getName());
                            application.setSupplyDeptId(deptList.get(m).getId());
                            btnSupplyDept.setText(deptList.get(m).getName());
                            break;
                        }
                    }
                    for (int n = 0; n < approvalList.size(); n++) {
                        if (approvalList.get(n).getIsDefault()) {
                            application.setApprovalId(approvalList.get(n).getId());
                        }
                    }
                    application.setVaccineType(category.get(position));
                    if (category.get(position).equals("1")) {
                        btnVaccineType.setText("免疫规划");
                    } else if (category.get(position).equals("2")) {
                        btnVaccineType.setText("非免疫规划");
                    } else if (category.get(position).equals("3")) {
                        btnVaccineType.setText("配套品");
                    }
                    application.setSourceId(sourceId.get(position));
                    application.setVaccineType(category.get(position));
                    application.setRunTime(btnStartTime.getText().toString());
                    application.setArrivalTime(btnEndTime.getText().toString());
                    notifyDataSetChanged();
                    popup.dismiss();
                }
            });
            return convertView;
        }
    }

    public class HolderView {//由于这里用户都是同一个人,就省略用户图像的刷新
        private TextView text;
    }
    /*单选某些条件,type=1 运输设备,*/
    protected void showChoose(TextView textView,List<String> name, List<String> id,int type) {
        listView = new ListView(context);
        listView.setDivider(null);//设置分割线
        listView.setVerticalScrollBarEnabled(false);//不显示滑动条
        listView.setAdapter(new MyChooseAdapter(textView,name, id,type));
        popup = new PopupWindow(context);
        popup.setWidth(textView.getWidth());
        popup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.selector_unfocused));
        popup.setContentView(listView);//设置显示内容
        popup.setOutsideTouchable(true);//点击PopupWindow以外的区域自动关闭该窗口
        popup.showAsDropDown(textView, 0, 5);//显示在edit控件的下面0,0代表偏移量
        textView.setBackgroundResource(R.drawable.selector_focused);
        popup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                textView.setBackgroundResource(R.drawable.selector_unfocused);
            }
        });
    }

    //适配器
    private class MyChooseAdapter extends BaseAdapter {
        private List<String> name, id;
        private TextView textView;
        private int type;

        public MyChooseAdapter(TextView textView,List<String> name, List<String> id,int type) {
            this.name = name;
            this.id = id;
            this.type = type;
            this.textView = textView;
        }

        @Override
        public int getCount() {
            return name.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            HolderView holderView = null;
            if (convertView == null) {
                convertView = View.inflate(context, R.layout.item_dialog_login, null);
                holderView = new HolderView();
                holderView.text = (TextView) convertView.findViewById(R.id.tvStorage);
                convertView.setTag(holderView);
            } else {
                holderView = (HolderView) convertView.getTag();
            }
            if(textView.getText().toString().equals(name.get(position))){
                holderView.text.setTextColor(getResources().getColor(R.color.billChoosed));
            }
            holderView.text.setText(name.get(position));
            holderView.text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    textView.setText(name.get(position));
                    textView.setTextColor(getResources().getColor(R.color.billTextChoose));
                    notifyDataSetChanged();
                    textView.setBackgroundResource(R.drawable.selector_unfocused);
                    if(type==1){//运输设备
                        application.setColdChainType(id.get(position));
                    }else if (type==2){//运输单位
                        application.setTransformName(name.get(position));
                        application.setTransformId(id.get(position));
                    }


                    popup.dismiss();
                }
            });
            return convertView;
        }
    }
    /*弹窗*/
    protected void dialogReasonShow(PiatsInfo piatsInfo, int position) {
        LayoutInflater mLayoutInflater = LayoutInflater.from(this);
        View view = mLayoutInflater.inflate(R.layout.dialog_scrap, null);
        final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setView(view);
        _alertDialog = alertBuilder.create();
        _alertDialog.show();
        ScanUtil.powerOffScan(context);
        TextView btnCode = (TextView) view.findViewById(R.id.btnCode);
        TextView tvVaccineName = (TextView) view.findViewById(R.id.tvVaccineName);
        TextView tvCancel = (TextView) view.findViewById(R.id.tvCancel);
        TextView tvConfirm = (TextView) view.findViewById(R.id.tvConfirm);
        TextView btnReason = (TextView) view.findViewById(R.id.btnReason);
        TextView btnRuinTime = (TextView) view.findViewById(R.id.btnRuinTime);//销毁时间
        EditText btnReason2 = (EditText) view.findViewById(R.id.btnReason2);
        EditText btnReasonType = (EditText) view.findViewById(R.id.btnReasonType);
        if("RuinOutActivity".equals(simpleName)){
            btnReasonType.setVisibility(View.VISIBLE);
            btnRuinTime.setVisibility(View.VISIBLE);
            btnReason.setText("请选择销毁原因");
            btnReason2.setHint("请输入销毁原因");
        }
        if(!StringUtil.isNullOrEmpty(piatsInfo.getReason()))btnReason.setText(application.getReason(piatsInfo.getReason()));
        if(!StringUtil.isNullOrEmpty(piatsInfo.getOtherReason())&&"09".equals(piatsInfo.getOtherReason())){
            btnReason2.setText(application.getReason(piatsInfo.getReason()));
            btnReason2.setVisibility(View.VISIBLE);
        }
        RecyclerView rvReason = (RecyclerView) view.findViewById(R.id.rvReason);
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        rvReason.setLayoutManager(layoutManager);
        btnCode.setText(piatsInfo.getCode());
        btnReason.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rvReason.setVisibility(View.VISIBLE);
                ReasonAdapter storageAdapter = new ReasonAdapter(rvReason,btnReason,btnReason2, Arrays.asList(moveReasonName), Arrays.asList(moveReasonId));
                rvReason.setAdapter(storageAdapter);
            }
        });
        btnRuinTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getTimeDialog(btnRuinTime);
            }
        });
        tvVaccineName.setText(piatsInfo.getPhysicName());
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ScanUtil.powerOnScan(context);
                _alertDialog.dismiss();
            }
        });
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if("RuinOutActivity".equals(simpleName)){
                    if(btnRuinTime.getText().toString().equals("销毁时间")){
                        Toast.makeText(context,"请选择销毁时间",Toast.LENGTH_SHORT).show();
                        return;
                    }else if(btnReasonType.getText().toString().equals("")){
                        Toast.makeText(context,"请输入销毁时间",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    piatsInfo.setDestructTime(btnRuinTime.getText().toString());
                    piatsInfo.setDestructType(btnReasonType.getText().toString());
                }
                ScanUtil.powerOnScan(context);
                if(btnReason.getText().toString().trim().equals("包装无法识别")){
                    piatsInfo.setReason("01");piatsInfo.setOtherReason("");
                }else if(btnReason.getText().toString().trim().equals("超过有效期")){
                    piatsInfo.setReason("02");piatsInfo.setOtherReason("");
                }else if(btnReason.getText().toString().trim().equals("不符合储存温度要求")){
                    piatsInfo.setReason("03");piatsInfo.setOtherReason("");
                }else if(btnReason.getText().toString().trim().equals("其他")){
                    piatsInfo.setReason("09");piatsInfo.setOtherReason(btnReason2.getText().toString());
                }
                recyclerAdapter.notifyDataSetChanged();
                _alertDialog.dismiss();
            }
        });

    }
    private class ReasonAdapter extends RecyclerView.Adapter<ReasonAdapter.ViewHolder> {
        private List<String> reasonNameList;private List<String> reasonIdList;
        private TextView btnReason;private EditText btnReason2;private RecyclerView rvReason;
        public ReasonAdapter(RecyclerView rvReason,TextView btnReason,EditText btnReason2,List<String> reasonNameList,List<String> reasonIdList) {
            this.btnReason = btnReason;
            this.btnReason2 = btnReason2;
            this.reasonNameList = reasonNameList;
            this.reasonIdList = reasonIdList;
            this.rvReason = rvReason;
        }

        @NonNull
        @Override
        public ReasonAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_dialog_reason, parent, false);
            ReasonAdapter.ViewHolder viewHolder = new ReasonAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull ReasonAdapter.ViewHolder holder, int position) {
            holder.tvReason.setText(reasonNameList.get(position));
            holder.tvReason.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnReason.setText(reasonNameList.get(position));
                    btnReason.setTextColor(getResources().getColor(R.color.billTextChoose));
                    rvReason.setVisibility(View.GONE);
                    if(reasonIdList.get(position).equals("09")){
                        btnReason2.setVisibility(View.VISIBLE);
                    }else{
                        btnReason2.setVisibility(View.GONE);
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return reasonNameList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tvReason;
            public ViewHolder(View itemView) {
                super(itemView);
                this.tvReason = itemView.findViewById(R.id.tvReason);
            }
        }
    }



}
